  <template>
  <view class="container">
    <view style="height: 89vh;">
      <view class="nav-bar">
        <h3 class="font-title">
          <span class="top-title">您好，</span><br/>
          <span class="top-title-end">欢迎来到校园食品安全<span style="color: #3775F6" v-if="projectType=='education'">执法检查系统</span></span>
        </h3>
      </view>
      <view class="nav-bar">
        <view class="banner">
          <view class="input-view" :class="form.loginName ? 'uni-input' : 'uni-input-grey'">
            <uv-input v-model="form.loginName" focus placeholder="输入用户名" border="none"></uv-input>
          </view>
          <view class="input-view" style="margin-top:10px;" :class="form.loginPwd ? 'uni-input' : 'uni-input-grey'">
            <uv-input v-model="form.loginPwd" placeholder="输入密码" border="none" :password="passwordEye">
              <template v-slot:suffix>
                <view :class="[passwordEye ? 'icon-password-hide iconfont size' : 'icon-password iconfont size']" style="font-size: 36rpx;color: rgba(0, 0, 0, 0.26)" @click="changePassword"></view>
              </template>
            </uv-input>
          </view>
          <view class="button-view">
            <uv-button class="button" type="primary" @click="checkLogin" :disabled="button">登录</uv-button>
          </view>
          <view class="input-view input-box-bottom" style="font-size: 12px;margin-top: 5%">
            <uv-checkbox-group
                v-model="checkboxValue"
                shape="circle">
              <uv-checkbox name="go"></uv-checkbox>
            </uv-checkbox-group>
            已阅读并同意平台<span @click="goPage('login','agreement')" style="color:#1F7EF8">《用户协议》</span>及<span style="color:#1F7EF8" @click="goPage('login','policy')">《隐私政策》</span>
          </view>
          <uv-modal ref="personModal" title="服务协议及隐私保护" content='为了更好的保障您的合法权益，建议您阅读《用户协议》及《隐私政策》，确认后默认您阅读并同意登录平台' :closeOnClickOverlay="false"
                    showConfirmButton="true" showCancelButton="true"
                    @confirm="personConfirm" @cancel="personCancel">
          </uv-modal>
          <view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script setup>
import {reactive, ref, getCurrentInstance, watchEffect, inject} from 'vue';
import {getAES} from '@/utils/crypto'
import api from '@/api/login/login'
import config from '@/common/config'
import wechatApi from '@/api/wechat/wechatlogin'
import {onShow} from '@dcloudio/uni-app'
const {proxy} = getCurrentInstance();

let projectType = ref('');
projectType.value = config.PROJECT_TYPE;      // 默认系统登录名称

const form = reactive({
  loginName: '',
  loginPwd: ''
});
const button = ref(true);
//储存登录类型
const tabbarType = proxy.store().tabbar

let passwordEye = ref(true);

let checkboxValue = ref([]);

watchEffect(function (){
  if (form.loginName && form.loginPwd) {
    button.value = false;
  } else {
    button.value = true;
  }
})

let setUserOpenId = async (e) => {
  if (!uni.getStorageSync('openid')) {
    uni.showToast({title: '获取openid失败', icon: 'none'});
    clearStorage();
    return;
  }
  await proxy.http.asyncPost(wechatApi.setUserOpenId,{sysUserId:uni.getStorageSync('userInfo').user.id,openid:uni.getStorageSync('openid')});
};



// 账号登录
let accountLogin = async (e) => {
  let res = await proxy.http.asyncPost(api.accountLogin, {
    username: form.loginName.trim(),
    password: getAES(form.loginPwd),
    grant_type: 'password',
  }, true, "HEADER_JSON", "password", true);
  if (res.code === 0) {
    //存token
    uni.setStorageSync('token', res.data.accessToken);
    uni.setStorageSync('loginName', form.loginName);
    uni.setStorageSync('loginPwd', form.loginPwd);
    await getLoginInfo();
  } else {
    await uni.showToast({title: res.msg, icon: 'none'});
  }
}
const {userStore} = proxy.store();

const pcoLawIndexPermissions = config.PCO_LAW_INDEX_PERMISSIONS;
// 获取用户信息
let getLoginInfo = async (e) => {
  let res = await proxy.http.asyncGet(api.getLoginInfo, {}, true);
  if (res.code === 0) {
    await getMenu();
    //登录成功，并返回用户信息和主体信息
    uni.setStorageSync('userInfo', res.data);
    uni.setStorageSync('phone', res.data.user.phone);
    uni.setStorageSync('permissions', res.data.permissions);
    userStore.$patch(state => {
      state.permissions = res.data.permissions;
    })
    let userInfo = res.data.user;
    let permissions = res.data.permissions;
    if (userInfo.userType !== '00') {
      // 02:学校03配餐单位04供应商
      if (userInfo.org && userInfo.org.sourceType) {
          if ((userInfo.org.sourceType === '10') && projectType.value  === 'education') {      // 教育局
            if (permissions && permissions.includes(pcoLawIndexPermissions)) {
              await linkToPcoIndex(); // 有害生物执法系统
            } else {
              await linkToSchoolIndex(); // 原执法系统
            }
            tabbarType.$patch(state=>{
              state.type = 'education'
            })
          } else {
              await uni.showToast({title: '当前用户类型无法登录', icon: 'none'});
              clearStorage();
          }
      }
    } else {
      clearStorage();
      await uni.showToast({title: '当前用户类型无法登录', icon: 'none'});

    }

  } else {
    await uni.showToast({title: res.msg, icon: 'none'});
  }
}

// 获取用户菜单
let getMenu = async (e) => {
  let res = await proxy.http.asyncGet(api.getMenu, {}, true);
  if (res.code === 0) {
    let list = res.data || [];
    let menus = list.filter(item => {
      if (config.MENU_SOURCE.indexOf(item.menuSource) !== -1) {
        return item;
      }
    })
    uni.setStorageSync('menus', menus);
  } else {
    await uni.showToast({title: res.msg, icon: 'none'});
  }
};

let clearStorage = () => {
  uni.clearStorageSync();
};

// 调整到供应商首页
let linkToPurchaseIndex = async (e) => {
  uni.switchTab({
    url: '/pages/index/purchaseIndex',
    success: res => {
      uni.hideTabBar()
    }
  });
}

// 调整到学校首页
let linkToSchoolIndex = async (e) => {
  if(config.AUTHORISATION_ENABLE){
    setUserOpenId();
  }
  uni.reLaunch({
    url: '/pages/index/schoolIndex',
    success: res => {
      uni.hideTabBar()
    }
  });
}

// 调整到有害生物执法首页
let linkToPcoIndex = async (e) => {
  if(config.AUTHORISATION_ENABLE){
    setUserOpenId();
  }
  uni.reLaunch({
    url: '/pages/index/pcoLawIndex',
    success: res => {
      uni.hideTabBar()
    }
  });
}

// 忘记密码
let forgotPassword = (e) => {
  uni.navigateTo({
    url: "/pages/my/forgot-password"
  });
}

// 验证码登录
let changeLoginPage = (e) => {
  uni.navigateTo({
    url: '/pages/login/phone-login'
  });
}

let changePassword = (e) => {
  passwordEye.value = !passwordEye.value;
}


let buttonBg = (e) => {
  console.log('前==='+button.value)
  if (form.loginName && form.loginPwd) {
    button.value = false;
  } else {
    button.value = true;
  }
}
let close = (e) => {

}

const {tabbar} = proxy.store();
tabbar.$patch(state => {
  state.name = 'home';
})

// 隐私政策与用户协议
let goPage = (folder,file) => {
  uni.navigateTo({
    url: '/packageBase/pages/base/' + folder + '/' + file
  })
}

let personCancel = (e) => {
  proxy.$refs.personModal.close();
}
let personConfirm = (e) => {
  checkboxValue.value.push('go')
  accountLogin();
  proxy.$refs.personModal.close();
}

// 账号登录
let checkLogin = async (e) => {
  if (!form.loginName || !form.loginPwd) {
    await uni.showToast({title: '用户名或密码不能为空', icon: 'none'});
    return;
  }
  if(checkboxValue.value.length===0){
    proxy.$refs.personModal.open();
    return false;
  }
  await accountLogin();
}
// 自动登录
let silentLogin =() => {
  let loginName = uni.getStorageSync('loginName');      // 静默用户名
  let loginPwd = uni.getStorageSync('loginPwd');       // 静默密码
  if(loginName && loginPwd) {
    form.loginName = loginName;
    form.loginPwd = loginPwd;
    accountLogin();
  }
}
onLoad((option) => {
  if(config.AUTHORISATION_ENABLE){
    if(option && option.openid){
      uni.setStorageSync("openid",option.openid)
    }else{
      uni.clearStorageSync();
      uni.reLaunch({url: '/pages/login/web-login',});
    }
  }
});


onShow(() => {
  silentLogin();
})

</script>

<style lang="scss" scoped>
.container {
  width: 100vw;
  height: 100vh;
  position: relative;
  overflow: hidden;
}

.login-img {
  position: absolute;
  width: 100vw;
  height: 100vh;
  z-index: -1;
}

.nav-bar {
  width: 83%;
  margin-left: 7%;
  margin-right: 10%;
}

.top-title {
  font-size: 64rpx;
  font-weight: 600;
}

.top-title-end {
  font-size: 36rpx;
  font-weight: 600;
}

.line-height {
  line-height: 2;
}

.font-title {
  margin-top: 40%;
  font-weight: 500;
  font-family: HarmonyOS Sans SC;
}

.banner {
  width: 100%;
  overflow: hidden;
}

.input-view {
  margin-top: 15%;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-content: center;
  align-items: center;
}

.input-left {
  width: 80%;
  float: left;
}

.uni-input {
  border-bottom: 1px solid #F2F2F2;
  min-height: 40px;
}

.uni-input-grey {
  border-bottom: 1px solid #F2F2F2;
  min-height: 40px;
}

.forget {
  float: right;
  margin-top: 7%;
  color: #000000;
}

.icon-close {
  background-size: cover;
  width: 21px;
  height: 21px;
  float: right;
}

.button-view {
  margin-top: 15%;
}

.button {
  background: #3775F6;
  /*border: 1px solid #9BBAFA;*/
  color: #ffffff;
  padding: 0px;
  border-radius: 16rpx;
}

.phone-button-view {
  width: 83%;
  margin-left: 7%;
  margin-right: 10%;
  position: absolute;
  bottom: 5%;
}

.phone-login-button {
  border: 1px solid #266FE8;
  background: #ffffff;
  color: #000000;
  border-radius: 2px;
}

::v-deep .uv-button--info {
  background: none;
  color: #fff;
  border: none;
}

::v-deep .uv-button {
  height: 88rpx;
}

.input-box-bottom {
  width: 90vw;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  color: rgba(0, 0, 0, 0.4);
  .uv-link {
    flex: none;
    font-size: 24rpx;
  }
  ::v-deep .uv-checkbox-group {
    flex: none!important;
  }
}

.button-box{
  margin: 24rpx auto 0;
  width: 460rpx;
}
::v-deep .uv-input__content {
  height: 40px;
  line-height: 40px;
}

</style>
